import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class HashMapTest {
    public static void main(String[] args){
        // ======== 创建 HashMap
        HashMap<String, Integer> map = new HashMap<>();

        // ======== 添加元素
        map.put("Apple", 3);
        map.put("Banana", 2);
        map.put("Cherry", 5);

        // ======== 获取元素
        System.out.println("Apple's value: " + map.get("Apple"));

        // ======== 检查键/值是否存在
        System.out.println("Contains key 'Banana'? " + map.containsKey("Banana"));
        System.out.println("Contains value 5? " + map.containsValue(5));

        // ======== 遍历元素
        System.out.println("遍历方法一：");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
        System.out.println();

        System.out.println("遍历方法二：");
        map.forEach((key, value) -> System.out.println(key + " -> " + value));
        System.out.println();

        System.out.println("遍历方法三：");
        for (String key : map.keySet()) {
            System.out.println("Key: " + key + ", Value: " + map.get(key));
        }
        System.out.println();;

        // ======== 获取默认值
        System.out.println("Value of 'Grapes': " + map.getOrDefault("Grapes", 0));

        // ======== 删除元素
        map.remove("Cherry");
        System.out.println("After removal: " + map);

        // ======== 替换元素
        map.replace("Apple", 4);
        System.out.println("After replacement: " + map);

        // ======== 统计次数
        System.out.println("统计次数");
        HashMap<String, Integer> counts = new HashMap<>();
        String[] words = {"apple", "banana", "apple", "orange", "banana"};

        for (String word : words) {
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);

        // ======== 多个值，合并到一个键下
        System.out.println("多个值，合并到一个键下");
        HashMap<String, Set<String>> mergeMap = new HashMap<>();
        // ======== 使用 HashSet 的构造器添加元素
        Set<String> initialSet = new HashSet<>();
        initialSet.add("Math");
        mergeMap.merge("Alice", initialSet, (oldSet, newSet) -> {
            oldSet.addAll(newSet);
            return oldSet;
        });
        Set<String> additionalSet = new HashSet<>();
        additionalSet.add("Science");
        mergeMap.merge("Alice", additionalSet, (oldSet, newSet) -> {
            oldSet.addAll(newSet);
            return oldSet;
        });
        System.out.println(mergeMap); // {Alice=[Math, Science]}
    }
}
